package controllers

import (
	"context"
	"encoding/json"
	"github.com/Baidu-AIP/golang-sdk/aip/censor"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"shang/conmon"
	"shang/models"
	"strconv"
	"sync"
	"time"
)

type ImController struct {
	beego.Controller
}
type Message struct {
	FriendId int    `json:"friend_id" form:"friend_id"`
	Content  string `json:"content" form:"content"`
	GroupId  int    `json:"group_id" form:"group_id"`
	Cmd      int    `json:"cmd" form:"cmd"`
}
type Node struct {
	Conn   *websocket.Conn
	Data   chan []byte
	Userid string
}

var ClientMap = make(map[int]*Node)
var wg sync.WaitGroup

func (i *ImController) Im() {
	userid := conmon.Userid
	upgrade := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrade.Upgrade(i.Ctx.ResponseWriter, i.Ctx.Request, nil)
	if err != nil {
		log.Println("websocket连接失败", err)
		return
	}
	node := &Node{
		Conn:   conn,
		Data:   make(chan []byte, 50),
		Userid: strconv.Itoa(userid),
	}
	ClientMap[userid] = node
	wg.Add(2)
	go SendMsg(node)
	go ReadMsg(node)
	wg.Wait()
}

func SendMsg(node *Node) {
	defer wg.Done()
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println("实时获取信息失败", err)
		}
		var msg Message
		json.Unmarshal(message, &msg)

		if msg.Cmd == 1 {
			id, _ := strconv.Atoi(node.Userid)
			user, _ := models.GetFriendInfo(models.FriendTwo{
				UserId:   id,
				FriendId: msg.FriendId,
			})
			friend, _ := models.GetFriendInfo(models.FriendTwo{
				UserId:   msg.FriendId,
				FriendId: id,
			})
			if user.ID == 0 && friend.ID == 0 {
				log.Println("你俩还不是好友，请先添加好友")
				node.Conn.WriteMessage(websocket.TextMessage, []byte("你俩还不是好友，请先添加好友"))
				continue
			}
			friendMap, ok := ClientMap[msg.FriendId]
			if ok {
				friendMap.Data <- []byte(msg.Content)
			}
		} else {
			//todo: 禁言
			count, _ := strconv.Atoi(models.Redis.Get(context.Background(), "count:"+node.Userid).Val())
			jin := models.Redis.Get(context.Background(), node.Userid).Val()
			if jin == "" && count >= 3 {
				models.Redis.Del(context.Background(), "count:"+node.Userid)
				models.Redis.Del(context.Background(), node.Userid)
				count = 0
			}
			if count >= 3 {
				node.Conn.WriteMessage(websocket.TextMessage, []byte("你他妈又骂人，被禁言了！！！"))
				continue
			}
			//todo: 敏感词处理
			client := censor.NewClient("i7GMCPKC5KW1oox4QGUWIWzd", "RYRWeQoUmfvsHQzWtBY2INqG2QUudtIz")
			res := client.TextCensor(msg.Content)
			var resMap map[string]interface{}
			json.Unmarshal([]byte(res), &resMap)
			if resMap["conclusion"] == "不合规" {
				log.Println("您发送的消息不合规")
				msg.Content = "******"
				models.Redis.Incr(context.Background(), "count:"+node.Userid)
				s, _ := strconv.Atoi(models.Redis.Get(context.Background(), "count:"+node.Userid).Val())
				if s >= 3 {
					models.Redis.Set(context.Background(), node.Userid, "禁言", time.Minute*1)
				}
			}
			//todo: 群聊发消息
			group, _ := models.GetGroupAll(models.GroupTwo{
				GroupId: msg.GroupId,
			})
			for _, v := range group {
				if ClientMap[v.UserId] != node {
					friendMap, ok := ClientMap[v.UserId]
					if ok {
						friendMap.Data <- []byte(msg.Content)
					}
				}
			}

		}
	}
}
func ReadMsg(node *Node) {
	defer wg.Done()
	for {
		select {
		case data := <-node.Data:
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				log.Println("实时接收消息失败", err)
			}
		}
	}
}
